/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */

package com.poltman.dscentral.communities;

import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.Context;
import org.springframework.dao.DataAccessException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Button;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;


import com.poltman.dscentral.extended.services.CommunityExtendedService;
import com.poltman.dscentral.db.entity.dspace.CommunityEntity;
import com.poltman.dscentral.db.model.zul.CommunityEditionZulModel;
import com.poltman.dscentral.db.service.dspace.CommunityService;
import com.poltman.dscentral.core.CoreSessionData;
import com.poltman.dscentral.core.dspace.Communities;

/**
 * 
 * @author z.ciok@poltman.com
 *
 */
@SuppressWarnings("rawtypes")
public class SaveNewTopLevelCommunity extends SelectorComposer  {

	private static final long serialVersionUID = 3993933765365215551L;

	private static Logger log = Logger.getLogger(SaveNewTopLevelCommunity.class);
	
	@Wire
	Button saveBtn;
	
	@Wire
	Textbox nameTextbox;
	
	@Wire
	Textbox shortDescriptionTextbox;	
	
	@Wire
	Textbox handleTextbox;
	
	/**
	 * 
	 */
	@Listen("onClick = button#saveBtn")
	public void saveNewTopLevelCommunity() {
		CoreSessionData coreSessionData = (CoreSessionData) SpringUtil.getBean("coreSessionData");
		Context context = (Context) SpringUtil.getBean("context");
		try {
			//TODO: parent
			//check authorization
	        if (!(AuthorizeManager.isAdmin(context))) {
	        		//TODO: it's not top level community
	        		//|| (parent != null && AuthorizeManager.authorizeActionBoolean(context, parent, org.dspace.core.Constants.ADD)))) 
	              Messagebox.show("Only administrators can create communities.", "DSCentral Error", 0,  Messagebox.ERROR);
	              return;
	        }			
			
			//save community
			CommunityService  communityService = (CommunityService) SpringUtil.getBean("communityService");
			
			if ((nameTextbox.getValue() == null) || (nameTextbox.getValue().isEmpty())) {
				//TODO: i18n
				Messagebox.show("Name can not be null.", "DSCentral Error", 0,  Messagebox.ERROR);	
				return;
			} else {
				CommunityEntity communityEntity = communityService.findByName(nameTextbox.getValue());
				if (communityEntity != null) {
					String communityName = communityEntity.getName();
					if (communityName.equals(nameTextbox.getValue())) {
						//TODO: i18n
						Messagebox.show("Save error: " + nameTextbox.getValue() + " already exists.", "DSCentral Error", 0,  Messagebox.ERROR);
						return;
					}
				}
				
				CommunityEditionZulModel zulModel = new CommunityEditionZulModel();  
				zulModel.setName(nameTextbox.getValue());
				zulModel.setShortDescription(shortDescriptionTextbox.getValue());

				CommunityExtendedService communityExtendedService = (CommunityExtendedService) SpringUtil.getBean("communityExtendedService");
				zulModel = communityExtendedService.createTopLevelCommunity(zulModel);
				this.handleTextbox.setValue(zulModel.getHandle());
			}	
		} catch (DataAccessException e) {
			log.error("Error: ; ", e);
			//TODO: i18n
			Messagebox.show("Save error...", "DSCentral Error", 0,  Messagebox.ERROR);
			return;
		} catch (Exception e) {
			log.error("Error: ; ", e);
			//TODO: i18n
			Messagebox.show("Save error...", "DSCentral Error", 0,  Messagebox.ERROR);
			return;
		}
		
		//refresh tree
		Communities communities = (Communities) coreSessionData.getAttribute("NewTopLevelCommunities");
		try {
			CommunityUtils.refreshNewTopLevelCommunityTree(communities);
		} catch (Exception e) {
			log.error("saveNewTopLevelCommunity (refresh tree) ", e);
		}		
		
		//TODO: i18n
		Messagebox.show("New Top Level Community has been created...", "DSCentral", 0,  Messagebox.INFORMATION);
	}	
}
